package priv.xakml;

import priv.xakml.toolkit.BinaryConverter;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class FileHashTool {
    private  File _file = null;
    InputStream stream = null;
    public FileHashTool(File file){
        this._file = file;
    }

    /**
     *
     * @return
     */
    public String getMd5Value(){
        return  this.getMd5Value(this._file);
    }
    /**
     * 计算文件的MD5值
     * @param file
     * @return
     */
    public String getMd5Value(File file) {

        try {
            if(stream == null)
                stream = Files.newInputStream(file.toPath(), StandardOpenOption.READ);
            else
                stream.reset();
            MessageDigest digest = MessageDigest.getInstance("MD5");
            return computeHash(stream, digest);
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     *
     * @return
     */
    public String getSHA1Value(){
        return this.getSHA1Value(this._file);
    }
    /**
     *  计算文件的sha1值
     * @param file
     * @return
     */
    public String getSHA1Value(File file){
        InputStream stream = null;
        try {
            if(stream == null)
                stream = Files.newInputStream(file.toPath(), StandardOpenOption.READ);
            else
                stream.reset();
            MessageDigest digest = MessageDigest.getInstance("sha1");
            return computeHash(stream, digest);
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return "";
        }
    }
    private String computeHash(InputStream stream, MessageDigest digest) throws IOException {
        byte[] buf = new byte[8192];
        int len;
        while ((len = stream.read(buf)) > 0) {
            digest.update(buf, 0, len);
        }
        byte[] hash = digest.digest();
        String hash_hex = BinaryConverter.toHexString(hash, true);
        return hash_hex;
    }
}
